package qst.com.bacK.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import qst.com.bacK.Constant;
import qst.com.bacK.utils.RequestUtil;
import qst.com.bacK.utils.WebUtil;
import qst.com.bacK.exception.ExamException;
import qst.com.bacK.pojo.entity.*;
import qst.com.bacK.service.AssessmentService;
import qst.com.bacK.service.ExamService;
import qst.com.bacK.service.QuestionService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

import static qst.com.bacK.Constant.CURRENT_EXAM;

/**
 * Author:   msh
 * Date:     2024/10/9 下午10:38
 * Description:
 */

@Controller
@RequestMapping("/exam")
public class ExamController {
    @Autowired
    private ExamService examService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private AssessmentService assessmentService;

    @RequestMapping("/list")
    public String listSchedules(HttpSession session, Model model) {
        TestPersonnel personnel = (TestPersonnel) session.getAttribute(Constant.CURRENT_TESTPERSONNEL);
        List<Schedule> scheduleList = examService.findScheduleByTestPersonnel(personnel);
        model.addAttribute("scheduleList", scheduleList);
        return "exam/list"; // 这里假设list.jsp位于WEB-INF/views/exam目录下
    }

    // 进入考试
    @GetMapping("/begin")
    public String doAction(@RequestParam("id") Integer id, HttpSession session) {
        // 获取考试信息
        Exam exam = null;
        TestPersonnel testPersonnel = (TestPersonnel) session.getAttribute(Constant.CURRENT_TESTPERSONNEL);
        try {
            exam = examService.begin(testPersonnel, id);
            // 将考试信息保存到session中
            session.setAttribute(CURRENT_EXAM, exam);
            return "redirect:/exam/exam";
        } catch (ExamException e) {
            e.printStackTrace();
            session.setAttribute("_error_key", e.getMessage());
            return "redirect:/exam/list";
        }


    }


    // 显示考试结果
    @RequestMapping("/result")
    public void doAction(@RequestParam("id") Integer id, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Exam> exams = examService.examResult(id);
            String result = null;
            for (Exam e : exams) {
                result = e.getResult();
            }
            StringBuffer stf = new StringBuffer();
            stf.append("../analysis/");
            stf.append(result);
            stf.append(".jsp");
            req.setAttribute("exam", exams);
            req.setAttribute("examresult", stf.toString());
            WebUtil.forward(req, resp, "/exam/result.jsp");

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @RequestMapping("/exam")
    protected void exam(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Exam exam = (Exam) req.getSession().getAttribute(CURRENT_EXAM);

        int[] answer = RequestUtil.getIntArray(req, "answer");

        ExamQuestion eq = exam.getQuestion();
        eq.setAnswer(answer);

        int index = RequestUtil.getInt(req, "index");
        if (index == -3) {
            WebUtil.forward(req, resp, "/exam/end.action");
        } else {
            if (index == -2) {
                exam.setQuestionIndex(exam.getQuestionIndex() + 1);
            } else if (index == -1) {
                exam.setQuestionIndex(exam.getQuestionIndex() - 1);
            } else {
                exam.setQuestionIndex(index);
            }
            eq = exam.getQuestion();

            List<Choice> choices = eq.getQuestion().getChoices();
            if (choices == null) {
                choices = questionService.findChoices(eq.getQuestion().getId());
                Collections.shuffle(choices);
                eq.getQuestion().setChoices(choices);
            } else {
                for (Choice ch : choices) {
                    ch.getExtras().remove("checked");
                    if (eq.getAnswer() != null) {
                        for (int ans : eq.getAnswer()) {
                            if (ans == ch.getId()) {
                                ch.getExtras().put("checked", "checked");
                                break;
                            }
                        }
                    }
                }
            }

            req.setAttribute("exam", exam);
            req.getRequestDispatcher("/exam/exam.jsp").forward(req, resp);
        }
    }

    @RequestMapping("/end")
    public String doEndAction(HttpServletRequest req, HttpServletResponse resp) {
        Exam exam = (Exam) req.getSession().getAttribute(CURRENT_EXAM);
        try {
            assessmentService.end(exam);
            String resultPath = "../analysis/" + exam.getResult() + ".jsp";
            req.setAttribute("examresult", resultPath);
            req.setAttribute("score", exam.getResult());
        } catch (ExamException ex) {
            ex.printStackTrace();
            req.setAttribute("score", "您未能成功交卷，请重新交卷");
        }
        return "redirect:/exam/end.jsp"; // 使用重定向到视图
    }
}
